package com.xbh.Book.web;

import com.xbh.Book.pojo.Book;
import com.xbh.Book.pojo.Page;
import com.xbh.Book.service.BookService;
import com.xbh.Book.service.impl.BookServiceImpl;
import com.xbh.Book.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: JavaWebExer
 * @description:
 * @author: 许宝华
 * @create: 2021-04-27 15:33
 */

public class ClientBookServlet extends BaseServlet {
    BookService bookService=new BookServiceImpl();
    /**
     * 处理前台分页功能
     * @param req
     * @param resp
     * @return void
     * @author 许宝华
     * @creed: Talk is cheap,show me the code
     * @date 2021/4/24 16:30
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数pageNo和pageSize
        //第一次访问page， pageNo、pageSize为空，使用默认值
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize=WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //调用bookService.page(pageNo,pageSize):page对象
        Page<Book> page=bookService.page(pageNo,pageSize);
        page.setUrl("client/bookServlet?action=page");

        //保存Page对象到Request域中
        req.setAttribute("page",page);
        //请求转发到pages/manager/book_manager.jsp页面
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
    /**
     * 通过价格进行分页
     * @param req
     * @param resp
     * @return void
     * @author 许宝华
     * @creed: Talk is cheap,show me the code
     * @date 2021/4/24 16:30
     */
    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数pageNo和pageSize
        //第一次访问page， pageNo、pageSize为空，使用默认值
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize=WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = WebUtils.parseInt(req.getParameter("min"), 0);
        int max=WebUtils.parseInt(req.getParameter("max"), Integer.MAX_VALUE);
        //调用bookService.page(pageNo,pageSize):page对象
        Page<Book> page=bookService.pageByPrice(pageNo,pageSize,min,max);

        StringBuilder sb=new StringBuilder("client/bookServlet?action=pageByPrice");
        //如果有最小价格的参数，追加到分页条的参数中
        if(req.getParameter("min")!=null){
            sb.append("&min=").append(req.getParameter("min"));
        }
        if(req.getParameter("max")!=null){
            sb.append("&max=").append(req.getParameter("max"));
        }
        page.setUrl(sb.toString());

        //保存Page对象到Request域中
        req.setAttribute("page",page);
        //请求转发到pages/manager/book_manager.jsp页面
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
}
